import pymongo
from pymongo import MongoClient
import datetime
from bson import BSON

class Storage:    
    def __init__(self, IP="140.112.170.32"):
        self.client = None
        self.post = None
        self.post_id=None
        self.posts = None
        self.db = None
        self.collection = None
        self.ip=IP
        self.post_device=None
        self.bson_device=None

        self.post_sensor=None
        post_id_s=None
        print self.ip
        
                  
    def CreateSystem(self):
        self.client = MongoClient(self.ip, 27017)
        self.db = self.client["wuk_db"]
        self.collection = self.db["wuk_co"]
        print 'connected.'


    def bson_devic(self,Device):
        self.bson_device = BSON.encode({"mac_address": "%s_addr" %(Device),
        "SystemParameter" : "parameters",
        "Sensor" : "sensors",
        "Actuator" : "actuators"
        })
        #return self.bson_device #doesn't work...
        #print self.bson_device
        #print self.bson_device.decode()

    def AddDevice(self,houseId, Device):
        self.post_device = {"house_id": "%s" %(houseId),
        "data" : self.bson_devic(Device)
        }
        #print self.post_device
        #self.posts = self.db.posts 
        self.post_id = self.db.posts.insert(self.post_device)
        print self.db.posts.find_one({"house_id":"HouseID-a"})

    def bson_sensor(self,Sensor):
        self.bson_device = BSON.encode({"Type": "%s_type" %(Sensor),
        "ActionType" : "ActionType",
        "dimension" : "dimension",
        "value" : "value",
        "values":"values"
        })


    def AddSensor(self,houseId, deviceId, Sensor):
        self.post_sensor = {"house_id": "%s" %(houseId),
        "location":"Location of %s" %(houseId),
        "timestamp": datetime.datetime.utcnow(),
        "data" : self.bson_sensor(Sensor)
        }
        self.post_id_s = self.db.posts.insert(self.post_sensor)
        print self.db.posts.find_one(self.post_id_s)

st=Storage("140.112.170.32")
#st=Storage("127.0.0.1")
st.CreateSystem()

st.AddDevice("HouseID-a","Device-a")
st.AddSensor("HouseID-b","Device-b","Sensor-b")
#st.bson_devic("show pu")

'''
    def AddDevice(houseId, Device):
    def AddSensor(houseId, deviceId, Sensor):
    def AddActuator(houseId, deviceId, Actuator):
    def StoreSensorData(SensorData):
    def StorageContextData(ContextData):
    def FetchSensorDataInTimeRange(...):
    def FetchSensorDataInLocation(...):
    def FetchSensorData(...):
   '''

'''
    def bson_device(self,Device) : #instead of JSON, is it protobuf? #it seems like it will sort title automatically??
        self.bson_device = BSON.encode({"mac_address": "%s_addr" %(Device),
        "SystemParameter" : "parameters",
        "Sensor" : "sensors",
        "Actuator" : "actuators"
        })
        #print bson_string.decode()

'''